import { defineStore } from 'pinia'
import { reqUserLogin } from '@/api/user'
import { Profile } from '@/api/user.types'

const userStore = defineStore({
  // 唯一标识
  id: 'user',
  // 开启持久化插件
  persist: true,
  // 相当于 data
  state: () => {
    return {
      // 用户资料
      profile: {
        id: '',
        nickname: '游客',
        token: ''
      } as Profile
    }
  },
  // 相当于 computed
  getters: {
    isLogin (): boolean {
      return !!this.profile.token
    }
  },
  // 相当于 methods
  actions: {
    // ✨ 可以直接写异步或者同步逻辑
    setProfile (profile: Profile) {
      this.profile = profile
    },
    clearUser () {
      this.profile = {} as Profile
    },
    async login (form: { account: string, password: string }) {
      const { result } = await reqUserLogin(form)
      this.profile = result
    }
  }
  // 🚧注意：Pinia 没有 mutations
})

export default userStore
